import { StateType } from '@/App';
import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import { getCode, getToken } from '@/store/action/login';
import { Toast } from 'antd-mobile';
import { useFormik } from 'formik';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory } from 'react-router-dom';
import styles from './index.module.scss';

export default function Login() {
  const history = useHistory<StateType>();
  const ref = useRef(-1);
  const dispatch = useDispatch();
  const [count, setCount] = useState(0);
  const formik = useFormik({
    initialValues: {
      mobile: '13811111111',
      code: '702264',
    },
    onSubmit: async (values) => {
      await dispatch(getToken(values));
      console.log(history.location);
      if (history.location.state && history.location.state.from !== '/login') {
        // 回到退回前的页面
        history.push(history.location.state.from);
      } else {
        history.push('/');
      }
      Toast.show({ content: '登录成功' });
    },
    validate: (value) => {
      let errors = {} as { mobile: string; code: string };
      if (!/^1[3-9]\d{9}$/.test(value.mobile)) {
        errors.mobile = '手机号格式错误';
      }
      if (!/^\d{6}$/.test(value.code)) {
        errors.code = '验证码格式错误';
      }
      return errors;
    },
  });
  useEffect(() => {
    return () => {
      clearInterval(ref.current);
    };
  }, []);
  const handleCode = () => {
    dispatch(getCode(formik.values.mobile));
    setCount(60);
    ref.current = window.setInterval(() => {
      setCount((newCount) => {
        if (newCount === 1) clearInterval(ref.current);

        return newCount - 1;
      });
    }, 1000);
  };
  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={formik.handleSubmit}>
          {/* 手机号输入框 */}
          <div className="input-item">
            <div className="input-box">
              <Input
                autoFocus
                className="input"
                placeholder="请输入手机号"
                autoComplete="off"
                type="text"
                name="mobile"
                maxLength={11}
                errorMsg={formik.touched.mobile ? formik.errors.mobile : ''}
                value={formik.values.mobile}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              ></Input>
            </div>
          </div>

          {/* 短信验证码输入框 */}
          <div className="input-item">
            <div className="input-box">
              <Input
                extra={
                  count === 0 ? (
                    <span onClick={handleCode}>获取验证码</span>
                  ) : (
                    <span>{count}s后再次获取</span>
                  )
                }
                className="input"
                placeholder="请输入验证码"
                autoComplete="off"
                type="text"
                name="code"
                maxLength={6}
                errorMsg={formik.touched.code ? formik.errors.code : ''}
                value={formik.values.code}
                onChange={formik.handleChange}
                onBlur={formik.handleBlur}
              ></Input>
            </div>
          </div>

          {/* 登录按钮 */}
          <button
            type="submit"
            className="login-btn"
            disabled={!formik.isValid}
          >
            登录
          </button>
        </form>
      </div>
    </div>
  );
}
